package versi.vitro.oaiserviceprovider.service.validation.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.xml.transform.Source;

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import versi.vitro.oaiserviceprovider.service.validation.api.ValidationHelper;
import versi.vitro.oaiserviceprovider.service.validation.api.ValidationService;

public class ValidationServiceTest {

    private Mockery context;

    @BeforeMethod
    public void setUp() {
	context = new Mockery();
    }

    @Test
    public void testAddSchema() {

	final List<String> schemaLocations = new ArrayList<String>();
	schemaLocations.add("schemaNames0");
	schemaLocations.add("schemaNames1");
	final String[] schemaNameArray = new String[schemaLocations.size()];
	schemaLocations.toArray(schemaNameArray);

	final File file0 = new File("schemaNames0");
	final File file1 = new File("schemaNames0");
	final List<File> files = Arrays.asList(file0, file1);

	final List<Source> schemas = new ArrayList<Source>();

	final ValidationHelper validationHelper = context.mock(ValidationHelper.class);
	context.checking(new Expectations() {
	    {
		exactly(1).of(validationHelper).addFiletoSchemas(file0, schemas);
		will(returnValue(schemas));
		exactly(1).of(validationHelper).addFiletoSchemas(file1, schemas);
		will(returnValue(schemas));
	    }
	});

	ValidationService validationService = new ValidationServiceImpl(validationHelper, schemas) {
	    private int callIndex = 0;

	    protected File createFile(String location) {
		return files.get(callIndex++);
	    }
	};
	validationService.addSchemas(schemaNameArray);

	context.assertIsSatisfied();
    }

    @Test
    public void testValidateAgainstSchemas() {

	String dummyXml = "<root></root>";
	final byte[] bytes = dummyXml.getBytes();

	List<Source> schemas = new ArrayList<Source>();
	Source source0 = new Source() {

	    public String getSystemId() {
		return "SystemId0";
	    }

	    public void setSystemId(String systemId) {
	    }
	};
	Source source1 = new Source() {

	    public String getSystemId() {
		return "SystemId1";
	    }

	    public void setSystemId(String systemId) {
	    }
	};
	schemas.add(source0);
	schemas.add(source1);
	final Source[] schemaArray = new Source[schemas.size()];
	schemas.toArray(schemaArray);

	final ValidationHelper validationHelper = context.mock(ValidationHelper.class);
	context.checking(new Expectations() {
	    {
		exactly(1).of(validationHelper).validateAgainstSchema(bytes, schemaArray);
		will(returnValue(true));
	    }
	});

	ValidationService validationService = new ValidationServiceImpl(validationHelper, schemas);
	boolean isValid = validationService.validateAgainstSchemas(bytes);

	assert isValid;
	context.assertIsSatisfied();
    }
}
